/**
 * 全局语音播放器管理器
 * 确保同时只有一个播放器在播放
 */
import { VoiceSSEPlayer } from './voiceSSEPlayer'

class VoicePlayerManager {
  private currentPlayer: VoiceSSEPlayer | null = null
  private isPlaying = false

  /**
   * 播放语音
   */
  async play(url: string, options?: {
    sampleRate?: number
    timeout?: number
    onStart?: () => void
    onEnd?: () => void
    onError?: (error: string) => void
  }): Promise<void> {
    // 如果正在播放，直接返回，避免重复播放
    if (this.isPlaying) {
      return
    }

    try {
      this.isPlaying = true
      
      // 创建新的播放器
      this.currentPlayer = new VoiceSSEPlayer({
        sampleRate: options?.sampleRate ?? 22050,
        timeout: options?.timeout ?? 30000,
        onStart: () => {
          options?.onStart?.()
        },
        onEnd: () => {
          this.isPlaying = false
          this.currentPlayer = null
          options?.onEnd?.()
        },
        onError: (error) => {
          this.isPlaying = false
          this.currentPlayer = null
          options?.onError?.(error)
        }
      })

      await this.currentPlayer.play(url)
    } catch (error) {
      this.isPlaying = false
      this.currentPlayer = null
      throw error
    }
  }

  /**
   * 停止播放
   */
  stop(): void {
    if (this.currentPlayer) {
      this.currentPlayer.stop()
      this.currentPlayer = null
    }
    this.isPlaying = false
  }

  /**
   * 获取播放状态
   */
  getStatus(): 'idle' | 'playing' {
    return this.isPlaying ? 'playing' : 'idle'
  }

  /**
   * 检查是否正在播放
   */
  isCurrentlyPlaying(): boolean {
    return this.isPlaying
  }
}

// 导出单例实例
export const voicePlayerManager = new VoicePlayerManager()
